package fun.tan90.easy.binlog.manager.config.satoken.dao;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.session.SaSession;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/21 17:48
 */
@Slf4j
@Component
public class MysqlSaTokenDao implements SaTokenDao {

    @Override
    public String get(String key) {
        log.debug("get key {}", key);
        Row row = Db.selectOneBySql("SELECT object, effective_cutoff_time FROM binlog_sa_token WHERE token_key = ?", key);
        if (Objects.isNull(row)) {
            return null;
        }
        Date effectiveCutoffTime = row.getDate("effective_cutoff_time");
        if (effectiveCutoffTime.compareTo(new Date()) < 0) {
            return null;
        }
        return row.getString("object");
    }

    @Override
    public void set(String key, String value, long timeout) {
        log.debug("set key {} value {} timeout {}", key, value, timeout);
        if (timeout != 0L && timeout > SaTokenDao.NOT_VALUE_EXPIRE) {
            Row row = Db.selectOneById("binlog_sa_token", "token_key", key);
            String insert = "INSERT INTO binlog_sa_token (token_key, object, effective_cutoff_time, create_time) VALUES (?, ?, ?, ?)";
            String update = "update binlog_sa_token set object = ?, effective_cutoff_time = ? where token_key = ?";
            if (timeout == SaTokenDao.NEVER_EXPIRE) {
                if (Objects.isNull(row)) {
                    Db.insertBySql(insert, key, value, "9999-12-31 23:59:59", new Date());
                } else {
                    Db.updateBySql(update, value, "9999-12-31 23:59:59", key);
                }
            } else {
                if (Objects.isNull(row)) {
                    Db.insertBySql(insert, key, value, DateUtil.offsetSecond(new Date(), (int) timeout), new Date());
                } else {
                    Db.updateBySql(update, value, DateUtil.offsetSecond(row.getDate("effective_cutoff_time"), (int) timeout), key);
                }
            }
        }
    }

    @Override
    public void update(String key, String value) {
        log.debug("update key {} value {}", key, value);
        String update = "update binlog_sa_token set object = ? where token_key = ?";
        Db.updateBySql(update, value, key);
    }

    @Override
    public void delete(String key) {
        log.debug("delete key {}", key);
        Db.deleteById("binlog_sa_token", "token_key", key);
    }

    @Override
    public long getTimeout(String key) {
        log.debug("getTimeout key {}", key);
        Row row = Db.selectOneBySql("SELECT effective_cutoff_time FROM binlog_sa_token WHERE token_key = ?", key);
        if (Objects.isNull(row)) {
            return SaTokenDao.NOT_VALUE_EXPIRE;
        }
        Date effectiveCutoffTime = row.getDate("effective_cutoff_time");
        long between = DateUtil.between(new Date(), effectiveCutoffTime, DateUnit.SECOND);
        return between < 0 ? SaTokenDao.NOT_VALUE_EXPIRE : between;
    }

    @Override
    public void updateTimeout(String key, long timeout) {
        log.debug("updateTimeout key {} timeout {}", key, timeout);
        String update = "update binlog_sa_token set effective_cutoff_time = effective_cutoff_time + ? where token_key = ?";
        Db.updateBySql(update, timeout, key);
    }

    @Override
    public Object getObject(String key) {
        log.debug("getObject key {}", key);
        Row row = Db.selectOneBySql("SELECT object FROM binlog_sa_token WHERE token_key = ?", key);
        if (Objects.isNull(row)) {
            return null;
        }
        return JSON.parseObject(row.getString("object"), SaSession.class);
    }

    @Override
    public void setObject(String key, Object object, long timeout) {
        log.debug("setObject key {} object {} timeout {}", key, object, timeout);
        if (timeout != 0L && timeout > SaTokenDao.NOT_VALUE_EXPIRE) {
            String insert = "INSERT INTO binlog_sa_token (token_key, object, effective_cutoff_time, create_time) VALUES (?, ?, ?, ?)";
            if (timeout == SaTokenDao.NEVER_EXPIRE) {
                Db.insertBySql(insert, key, JSON.toJSONString(object, SerializerFeature.WriteClassName), "9999-12-31 23:59:59", new Date());
            } else {
                Db.insertBySql(insert, key, JSON.toJSONString(object, SerializerFeature.WriteClassName), DateUtil.offsetSecond(new Date(), (int) timeout), new Date());
            }
        }
    }

    @Override
    public void updateObject(String key, Object object) {
        log.debug("updateObject key {} object {}", key, object);
        String update = "update binlog_sa_token set object = ? where token_key = ?";
        Db.updateBySql(update, JSON.toJSONString(object, SerializerFeature.WriteClassName), key);
    }

    @Override
    public void deleteObject(String key) {
        log.debug("deleteObject key {}", key);
        Db.deleteById("binlog_sa_token", "token_key", key);
    }

    @Override
    public long getObjectTimeout(String key) {
        log.debug("getObjectTimeout key {}", key);
        Row row = Db.selectOneBySql("SELECT effective_cutoff_time FROM binlog_sa_token WHERE token_key = ?", key);
        if (Objects.isNull(row)) {
            return SaTokenDao.NOT_VALUE_EXPIRE;
        }
        return DateUtil.between(new Date(), row.getDate("effective_cutoff_time"), DateUnit.SECOND);
    }

    @Override
    public void updateObjectTimeout(String key, long timeout) {
        log.debug("updateObjectTimeout key {} timeout {}", key, timeout);
        String update = "update binlog_sa_token set effective_cutoff_time = ? where token_key = ?";
        Db.updateBySql(update, DateUtil.offsetSecond(new Date(), (int) timeout), key);
    }

    @Override
    public List<String> searchData(String prefix, String keyword, int start, int size, boolean sortType) {
        log.debug("searchData key {} keyword {} start {} size {} sortType {} ", prefix, keyword, start, size, sortType);
        return new ArrayList<>();
    }
}
